import React, { useRef, useState } from 'react';
import { DownloadOutlined, UploadOutlined } from '@ant-design/icons';
import {
  Button,
  Card,
  Col,
  Divider,
  Form,
  Input,
  message,
  Row,
  Select,
  Space,
  Spin,
  Typography,
  Upload,
} from 'antd';
import { genChart } from '@/services/ant-design-pro/api';
import EChartsReact from 'echarts-for-react';

const { Paragraph } = Typography;

const { Option } = Select;

// 表单项布局配置
const formItemLayout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 14 },
};

// 生成图表组件
const GenChart: React.FC = () => {
  const [chartName, setChartName] = useState<string>();
  const [chart, setChart] = useState<API.GenChartResult>();
  const [submitting, setSubmitting] = useState<boolean>(false);
  const echartsRef = useRef<any>();
  const downloadImage = () => {
    const chartInstance = echartsRef.current.getEchartsInstance();
    const dataURL = chartInstance.getDataURL({
      type: 'png',
      pixelRatio: 5,
    });
    const link = document.createElement('a');
    link.href = dataURL;
    link.download = chartName ? `${chartName}.png` : 'favicon.ico';
    link.click();
  };

  // 处理表单提交事件
  const onFinish = async (values: any) => {
    setChart(undefined);
    setSubmitting(true);
    const params = {
      ...values,
      file: undefined,
    };
    const res = await genChart(params, {}, values.file.file);
    setSubmitting(false);
    if (res.code !== 0) {
      message.error(res.message);
      return;
    }
    if (res.data) {
      let chartOption = null;
      try {
        chartOption = JSON.parse(res.data.resultChart ?? '{}');
        chartOption.title = undefined;
      } catch (e) {
        chartOption = {
          title: {
            text: '图表样式解析失败，可尝试重新生成',
            left: 'center',
            textStyle: {
              color: '#1890FF',
            },
          },
        };
      }
      res.data.resultChart = JSON.stringify(chartOption);
    }
    setChart(res.data);
  };

  return (
    <div>
      <Row gutter={24}>
        <Col span={12}>
          <Card title="智能分析">
            <Form name="validate_other" {...formItemLayout} onFinish={onFinish}>
              <Form.Item name="chartName" label="图表名称">
                <Input value={chartName} onChange={(e) => setChartName(e.target.value)} />
              </Form.Item>

              <Form.Item name="type" label="图表类型" hasFeedback>
                <Select>
                  <Option value="折线图">折线图</Option>
                  <Option value="柱状图">柱状图</Option>
                  <Option value="堆叠图">堆叠图</Option>
                  <Option value="散点图">散点图</Option>
                  <Option value="饼图">饼图</Option>
                  <Option value="雷达图">雷达图</Option>
                  <Option value="K线图">K线图</Option>
                  <Option value="漏斗图">漏斗图</Option>
                  <Option value="3D柱状图">3D柱状图</Option>
                  <Option value="3D散点图">3D散点图</Option>
                </Select>
              </Form.Item>

              <Form.Item
                name="goal"
                label="分析诉求"
                rules={[
                  {
                    required: true,
                    message: '请输入分析诉求',
                  },
                ]}
              >
                <Input.TextArea showCount maxLength={200} />
              </Form.Item>

              <Form.Item
                name="file"
                label="原始数据"
                extra=".xlsx .xls格式"
                rules={[
                  {
                    required: true,
                    message: '请上传原始数据',
                  },
                ]}
              >
                <Upload listType={'picture'} name="file" maxCount={1} beforeUpload={() => false}>
                  <Button icon={<UploadOutlined />}>上传文件</Button>
                </Upload>
              </Form.Item>

              <Form.Item wrapperCol={{ span: 12, offset: 6 }}>
                <Space>
                  <Button
                    type="primary"
                    htmlType="submit"
                    loading={submitting}
                    disabled={submitting}
                  >
                    智能分析
                  </Button>
                  <Button htmlType="reset">重置</Button>
                </Space>
              </Form.Item>
            </Form>
          </Card>
        </Col>
        <Col span={12}>
          <Card title="分析图表">
            {chart?.resultChart ? (
              <>
                <DownloadOutlined onClick={() => downloadImage()} style={{ float: 'right' }} />
                <div style={{ marginBottom: 16 }} />
                <EChartsReact ref={echartsRef} option={JSON.parse(chart?.resultChart)} />
              </>
            ) : !submitting ? (
              <div>请先在左侧提交分析数据</div>
            ) : null}
            <Spin spinning={submitting} />
          </Card>
          <Divider />
          <Card title="分析结论">
            {chart?.resultText ? (
              <Paragraph copyable>{chart.resultText}</Paragraph>
            ) : !submitting ? (
              <div>请先在左侧提交分析数据</div>
            ) : null}
            <Spin spinning={submitting} />
          </Card>
        </Col>
      </Row>
    </div>
  );
};
export default GenChart;
